package com.ruoyi.common.valid.emun;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 枚举类的code校验器
 *
 * @author HHKJ-SERVER-ZJ 2022/6/21 16:01
 */
public class EnumListChecker implements ConstraintValidator<EnumListCheck, Object>
{

    // 枚举校验注解
    private EnumListCheck annotation;

    @Override
    public void initialize(EnumListCheck constraintAnnotation)
    {

        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object objectList, ConstraintValidatorContext constraintValidatorContext)
    {
        Class<?> cls = annotation.target();
        boolean ignoreEmpty = annotation.ignoreEmpty();
        if (objectList instanceof List<?> && cls.isEnum()) {
            Object[] enums = cls.getEnumConstants();

            Set<String> enumStrSet = new HashSet<>();
            for (Object anEnum : enums) {
                enumStrSet.add(anEnum.toString());
            }
            for (Object value : (List<?>) objectList) {
                if (!enumStrSet.contains(value.toString())) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
}
